package com.unience.ec2.eclipse.treeviewer.ui;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Decorations;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;

import com.unience.aws.monitor.AwsMonitorThread;
import com.unience.aws.monitor.Ec2InstancesListener;
import com.unience.aws.monitor.model.MonitorEc2Instance;
import com.unience.ec2.eclipse.OpenViewAction;
import com.unience.ec2.eclipse.config.Config;
import com.unience.ec2.eclipse.config.UtilSWT;
import com.unience.ec2.eclipse.dialog.Ec2InstanceInfoDialog;
import com.unience.ec2.eclipse.dialog.ImageDescriptionDialog;
import com.unience.ec2.eclipse.dialog.NewEc2InstanceDialog;
import com.unience.ec2.eclipse.model.Ec2Image;
import com.unience.ec2.eclipse.model.Ec2Info;
import com.unience.ec2.eclipse.model.Ec2Instance;
import com.unience.ec2.eclipse.model.Model;
import com.unience.ec2.eclipse.model.SecurityGroup;
import com.unience.ec2.eclipse.view.Ec2ShellView;
import com.unience.ec2.test.LaunchEc2InstanceTest;
import com.unience.util.Dos2Unix;
import com.xerox.amazonws.ec2.EC2Exception;
import com.xerox.amazonws.ec2.GroupDescription;
import com.xerox.amazonws.ec2.ImageDescription;
import com.xerox.amazonws.ec2.ReservationDescription.Instance;

/**
 * Insert the type's description here.
 * 
 * @see ViewPart
 */
public class MovingBoxView extends ViewPart implements Ec2InstancesListener {

	private static IWorkbenchWindow window;

	public void update(final Collection<MonitorEc2Instance> instancesList,
			final Object listener) {

		Config.getInstance().getDisplay().asyncExec(new Runnable() {
			public void run() {

				MovingBoxView monitor = (MovingBoxView) listener;
				final IWorkbench workbench = PlatformUI.getWorkbench();
				if (workbench == null)
					return;
				final Display display = workbench.getDisplay();

				int numInstances = instancesList.size();
				if (!display.isDisposed()) {
					log.info("updating chart numInstances " + numInstances);
					monitor.getInstancesNode().getEc2Instances().clear();

					Iterator iterator = instancesList.iterator();

					while (iterator.hasNext()) {
						MonitorEc2Instance instance = (MonitorEc2Instance) iterator
								.next();
						monitor.getInstancesNode().getEc2Instances().add(
								new Ec2Instance(instance));
					}

					monitor.getTreeViewer().refresh();
				}
			}
		});

	}

	private static Log log = LogFactory.getLog(MovingBoxView.class);

	public static final String ID = "com.unience.ec2.eclipse.treeviewer.ui.MovingBoxView";

	protected TreeViewer treeViewer;
	protected Text text;
	protected MovingBoxLabelProvider labelProvider;

	protected Action onlyBoardGamesAction, atLeatThreeItems;
	protected Action booksBoxesGamesAction, noArticleAction;
	protected Action addBookAction, removeAction;
	protected ViewerFilter onlyBoardGamesFilter, atLeastThreeFilter;
	protected ViewerSorter booksBoxesGamesSorter, noArticleSorter;

	protected Ec2Info root;
	protected Ec2Info instancesNode;

	protected AwsMonitorThread updater;

	/**
	 * The constructor.
	 */
	public MovingBoxView() {

	}

	/*
	 * @see IWorkbenchPart#createPartControl(Composite)
	 */
	public void createPartControl(Composite parent) {
		/*
		 * Create a grid layout object so the text and treeviewer are layed out
		 * the way I want.
		 */
		GridLayout layout = new GridLayout();
		layout.numColumns = 1;
		layout.verticalSpacing = 2;
		layout.marginWidth = 0;
		layout.marginHeight = 2;
		parent.setLayout(layout);

		/*
		 * Create a "label" to display information in. I'm using a text field
		 * instead of a lable so you can copy-paste out of it.
		 */
		text = new Text(parent, SWT.READ_ONLY | SWT.SINGLE | SWT.BORDER);
		// layout the text field above the treeviewer
		GridData layoutData = new GridData();
		layoutData.grabExcessHorizontalSpace = true;
		layoutData.horizontalAlignment = GridData.FILL;
		text.setLayoutData(layoutData);

		// Create the tree viewer as a child of the composite parent
		treeViewer = new TreeViewer(parent);
		treeViewer.setContentProvider(new MovingBoxContentProvider());
		labelProvider = new MovingBoxLabelProvider();
		treeViewer.setLabelProvider(labelProvider);

		treeViewer.setUseHashlookup(true);

		// layout the tree viewer below the text field
		layoutData = new GridData();
		layoutData.grabExcessHorizontalSpace = true;
		layoutData.grabExcessVerticalSpace = true;
		layoutData.horizontalAlignment = GridData.FILL;
		layoutData.verticalAlignment = GridData.FILL;
		treeViewer.getControl().setLayoutData(layoutData);

		// Create menu, toolbars, filters, sorters.
		createFiltersAndSorters();
		createActions();
		createMenus();
		createToolbar();
		hookListeners();

		treeViewer.setInput(getInitalInput());

		treeViewer.addDoubleClickListener(new TreeDoubleClickListerner(this
				.getSite().getWorkbenchWindow()));
		treeViewer.getTree().setMenu(createPopUpMenu(parent.getShell()));

		treeViewer.expandAll();

		// updater = new UpdateEc2InstanceThread(this);

		// updater.start();

		updater = Config.getInstance().getUpdater();

		updater.addListener(this);
		updater.start();

		window = this.getSite().getWorkbenchWindow();

	}

	protected void createFiltersAndSorters() {
		atLeastThreeFilter = new ThreeItemFilter();
		onlyBoardGamesFilter = new BoardgameFilter();
		booksBoxesGamesSorter = new BookBoxBoardSorter();
		noArticleSorter = new NoArticleSorter();
	}

	protected void hookListeners() {
		treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(SelectionChangedEvent event) {
				// if the selection is empty clear the label
				if (event.getSelection().isEmpty()) {
					text.setText("");
					return;
				}
				if (event.getSelection() instanceof IStructuredSelection) {
					IStructuredSelection selection = (IStructuredSelection) event
							.getSelection();
					StringBuffer toShow = new StringBuffer();
					for (Iterator iterator = selection.iterator(); iterator
							.hasNext();) {
						Object domain = (Model) iterator.next();
						String value = labelProvider.getText(domain);
						toShow.append(value);
						toShow.append(", ");
					}
					// remove the trailing comma space pair
					if (toShow.length() > 0) {
						toShow.setLength(toShow.length() - 2);
					}
					text.setText(toShow.toString());
				}
			}
		});
	}

	protected void createActions() {
		onlyBoardGamesAction = new Action("Only Board Games") {
			public void run() {
				updateFilter(onlyBoardGamesAction);
			}
		};
		onlyBoardGamesAction.setChecked(false);

		atLeatThreeItems = new Action("Boxes With At Least Three Items") {
			public void run() {
				updateFilter(atLeatThreeItems);
			}
		};
		atLeatThreeItems.setChecked(false);

		booksBoxesGamesAction = new Action("Books, Boxes, Games") {
			public void run() {
				updateSorter(booksBoxesGamesAction);
			}
		};
		booksBoxesGamesAction.setChecked(false);

		noArticleAction = new Action("Ignoring Articles") {
			public void run() {
				updateSorter(noArticleAction);
			}
		};
		noArticleAction.setChecked(false);

		addBookAction = new Action("Add Ec2Instance") {
			public void run() {
				addNewEc2Instance();
			}
		};
		addBookAction.setToolTipText("Add a New Ec2Instance");
		// addBookAction.setImageDescriptor(TreeViewerPlugin.getImageDescriptor("newBook.gif"));

		removeAction = new Action("Delete") {
			public void run() {
				removeSelected();
			}
		};
		removeAction.setToolTipText("Delete");
		// removeAction.setImageDescriptor(TreeViewerPlugin.getImageDescriptor("remove.gif"));
	}

	/**
	 * Add a new book to the selected moving box. If a moving box is not
	 * selected, use the selected obect's moving box.
	 * 
	 * If nothing is selected add to the root.
	 */
	protected void addNewEc2Instance() {
		Ec2Info receivingBox;
		if (treeViewer.getSelection().isEmpty()) {
			receivingBox = root;
		} else {
			IStructuredSelection selection = (IStructuredSelection) treeViewer
					.getSelection();
			Model selectedDomainObject = (Model) selection.getFirstElement();
			if (!(selectedDomainObject instanceof Ec2Info)) {
				receivingBox = selectedDomainObject.getParent();
			} else {
				receivingBox = (Ec2Info) selectedDomainObject;
			}
		}
		receivingBox.add(Ec2Instance.newEc2Instance());
	}

	/**
	 * Remove the selected domain object(s). If multiple objects are selected
	 * remove all of them.
	 * 
	 * If nothing is selected do nothing.
	 */
	protected void removeSelected() {
		if (treeViewer.getSelection().isEmpty()) {
			return;
		}
		IStructuredSelection selection = (IStructuredSelection) treeViewer
				.getSelection();
		/*
		 * Tell the tree to not redraw until we finish removing all the selected
		 * children.
		 */
		treeViewer.getTree().setRedraw(false);
		for (Iterator iterator = selection.iterator(); iterator.hasNext();) {
			Model model = (Model) iterator.next();
			Ec2Info parent = model.getParent();
			parent.remove(model);
		}
		treeViewer.getTree().setRedraw(true);
	}

	protected void createMenus() {
		IMenuManager rootMenuManager = getViewSite().getActionBars()
				.getMenuManager();
		rootMenuManager.setRemoveAllWhenShown(true);
		rootMenuManager.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager mgr) {
				fillMenu(mgr);
			}
		});
		fillMenu(rootMenuManager);
	}

	protected void fillMenu(IMenuManager rootMenuManager) {
		IMenuManager filterSubmenu = new MenuManager("Filters");
		rootMenuManager.add(filterSubmenu);
		filterSubmenu.add(onlyBoardGamesAction);
		filterSubmenu.add(atLeatThreeItems);

		IMenuManager sortSubmenu = new MenuManager("Sort By");
		rootMenuManager.add(sortSubmenu);
		sortSubmenu.add(booksBoxesGamesAction);
		sortSubmenu.add(noArticleAction);
	}

	protected void updateSorter(Action action) {
		if (action == booksBoxesGamesAction) {
			noArticleAction.setChecked(!booksBoxesGamesAction.isChecked());
			if (action.isChecked()) {
				treeViewer.setSorter(booksBoxesGamesSorter);
			} else {
				treeViewer.setSorter(null);
			}
		} else if (action == noArticleAction) {
			booksBoxesGamesAction.setChecked(!noArticleAction.isChecked());
			if (action.isChecked()) {
				treeViewer.setSorter(noArticleSorter);
			} else {
				treeViewer.setSorter(null);
			}
		}

	}

	/* Multiple filters can be enabled at a time. */
	protected void updateFilter(Action action) {
		if (action == atLeatThreeItems) {
			if (action.isChecked()) {
				treeViewer.addFilter(atLeastThreeFilter);
			} else {
				treeViewer.removeFilter(atLeastThreeFilter);
			}
		} else if (action == onlyBoardGamesAction) {
			if (action.isChecked()) {
				treeViewer.addFilter(onlyBoardGamesFilter);
			} else {
				treeViewer.removeFilter(onlyBoardGamesFilter);
			}
		}
	}

	protected void createToolbar() {
		IToolBarManager toolbarManager = getViewSite().getActionBars()
				.getToolBarManager();
		toolbarManager.add(addBookAction);
		toolbarManager.add(removeAction);
	}

	public Ec2Info getInitalInput() {

		Config config = Config.getInstance();
		LaunchEc2InstanceTest myec2 = config.getEc2Instance();

		root = new Ec2Info();
		instancesNode = new Ec2Info("Ec2 Instances");
		Ec2Info secGroups = new Ec2Info("Security Groups");
		// Ec2Info ec2Instances = new Ec2Info("More ec2Instances");
		Ec2Info images = new Ec2Info("Ec2 Images (AMIs)");

		root.add(instancesNode);
		root.add(secGroups);
		root.add(images);

		/*
		 * JOAQUIN DIEZ
		 * 
		 * List<Instance> instances = myec2.checkInstances(); for (Instance
		 * instance:instances){ instancesNode.add(new Ec2Instance(instance));
		 * //TreeEc2Instance to = new TreeEc2Instance(instance);
		 * //p2.addChild(to); }
		 * 
		 */

		List<GroupDescription> securityCroups = myec2.getSecurityGroups();

		if (securityCroups != null) {

			for (GroupDescription group : securityCroups) {
				secGroups.add(new SecurityGroup(group, "Tigris & Euphrates",
						"Reiner", "Knizia"));
			}
		}

		List<ImageDescription> myImages = myec2.getMyImages();

		if (myImages != null) {
			for (ImageDescription myImage : myImages) {
				images.add(new Ec2Image(myImage, "dd", "dd", "dd"));
			}
		}

		return root;
	}

	/*
	 * @see IWorkbenchPart#setFocus()
	 */
	public void setFocus() {
	}

	class TreeDoubleClickListerner implements IDoubleClickListener {

		private final IWorkbenchWindow window;

		public TreeDoubleClickListerner(final IWorkbenchWindow window) {
			this.window = window;
		}

		public void doubleClick(DoubleClickEvent event) {
			log.info("DoubleClicked Tree");
			Object obj = event.getSource();

			log.info("object doubleClicked " + obj.getClass().getName());

			if (obj instanceof TreeViewer) {
				TreeViewer tree = (TreeViewer) obj;

				Object objectSelected = ((ITreeSelection) event.getSelection())
						.getFirstElement();
				log.info("object doubleClicked "
						+ objectSelected.getClass().getName());

				if (objectSelected instanceof SecurityGroup) {
					SecurityGroup securityGroupElem = (SecurityGroup) objectSelected;
					GroupDescription groupDesc = securityGroupElem
							.getGroupDescription();

					Config.getInstance().setLastSelection(groupDesc);

					/*
					 * if (openViewAction == null){
					 * 
					 * openViewAction = new OpenViewAction(window, "Open Another
					 * Ec2 GroupDescription View",
					 * SecurityGroupViewPart.ID_VIEW);
					 *  } openViewAction.run();
					 */
				}

				if (objectSelected instanceof Ec2Instance) {
					Ec2Instance ec2Instance = (Ec2Instance) objectSelected;
					Instance instance = ec2Instance.getEc2inst().getInstance();

					Config.getInstance().setLastSelection(instance);

					/*
					 * if (openViewAction == null){ openViewAction = new
					 * OpenViewAction(window, "Open Another Ec2 Instance
					 * View",InstanceViewPart.ID_VIEW); } openViewAction.run();
					 */
				}

				if (objectSelected instanceof Ec2Image) {
					Ec2Image treeObject = (Ec2Image) objectSelected;

					Config.getInstance().setLastSelection(
							treeObject.getImageDescription());
					/*
					 * if (openViewAction == null){ openViewAction = new
					 * OpenViewAction(window, "Open Another Ec2 Instance
					 * View",ImageViewPart.ID_VIEW); } openViewAction.run();
					 */
				}

			}

		}

	}

	private Menu createPopUpMenu(final Decorations parent) {
		final Menu menu = new Menu(parent, SWT.POP_UP);
		/*
		 * MenuItem item = new MenuItem(menu, SWT.PUSH); item.setText("Start Ec2
		 * Instance");
		 * 
		 * MenuItem item2 = new MenuItem(menu, SWT.PUSH); item2.setText("Stop
		 * Ec2 Instance");
		 */
		menu.addListener(SWT.Show, new Listener() {
			public void handleEvent(Event event) {
				MenuItem[] menuItems = menu.getItems();
				TreeItem[] treeItems = treeViewer.getTree().getSelection();

				for (int i = 0; i < menuItems.length; i++) {
					menuItems[i].dispose();
				}

				for (int i = 0; i < treeItems.length; i++) {
					TreeItem treeItem = treeItems[i];
					Object data = treeItem.getData();

					if (data instanceof Ec2Image) {
						Ec2Image ec2image = (Ec2Image) data;

						MenuItem item = new MenuItem(menu, SWT.PUSH);
						item.setText("Start Ec2 Instance");

						item.addSelectionListener(new MenuItemSelectionAdapter(
								ec2image.getImageDescription(),
								MenuItemSelectionAdapter.NONE));

						MenuItem item2 = new MenuItem(menu, SWT.PUSH);
						item2.setText("Get Info");

						item2
								.addSelectionListener(new MenuItemSelectionAdapter(
										ec2image.getImageDescription(),
										MenuItemSelectionAdapter.INFO));

					}
					if (data instanceof SecurityGroup) {
						SecurityGroup ec2secGroup = (SecurityGroup) data;
						// no menu options....
					}

					if (data instanceof Ec2Instance) {
						Ec2Instance ec2Instance = (Ec2Instance) data;
						MenuItem item = new MenuItem(menu, SWT.PUSH);
						item.setText("Stop Ec2 Instance");
						item.addSelectionListener(new MenuItemSelectionAdapter(
								ec2Instance.getEc2inst(),
								MenuItemSelectionAdapter.STOP));
						MenuItem item2 = new MenuItem(menu, SWT.PUSH);
						item2.setText("Instance Info");

						item2
								.addSelectionListener(new MenuItemSelectionAdapter(
										ec2Instance.getEc2inst(),
										MenuItemSelectionAdapter.INFO));

						MenuItem item3 = new MenuItem(menu, SWT.PUSH);
						item3.setText("Instance Shell");
						item3
								.addSelectionListener(new MenuItemSelectionAdapter(
										ec2Instance.getEc2inst(),
										MenuItemSelectionAdapter.SHELL));

						MenuItem item4 = new MenuItem(menu, SWT.PUSH);
						item4.setText("Instance Monitor");

						item4
								.addSelectionListener(new MenuItemSelectionAdapter(
										ec2Instance.getEc2inst(),
										MenuItemSelectionAdapter.MONITOR));

					}

					log.info("Tipo de dato : " + data.getClass());
				}

			}
		});

		return menu;
	}

	class MenuItemSelectionAdapter extends SelectionAdapter {
		private Object selectedObject;
		private String action = NONE;

		public static final String STOP = "STOP";
		public static final String INFO = "INFO";
		public static final String NONE = "NONE";
		public static final String SHELL = "SHELL";
		public static final String MONITOR = "MONITOR";

		public MenuItemSelectionAdapter(Object obj, String action) {
			super();
			selectedObject = obj;
			this.action = action;
		}

		private void doShowInfo() {
			MonitorEc2Instance instance = (MonitorEc2Instance) selectedObject;

			Ec2InstanceInfoDialog inst = new Ec2InstanceInfoDialog(UtilSWT
					.getShell(), SWT.NULL);

			inst.setMonitorInstance(instance);

			inst.open();
		}

		private void doShowShell() {
			MonitorEc2Instance instance = (MonitorEc2Instance) selectedObject;

			OpenViewAction openEc2ShellAction = new OpenViewAction(window,
					"OpenMonitor View", Ec2ShellView.ID_VIEW);
			openEc2ShellAction.run();
		}

		private void doShowMonitor() {
			MonitorEc2Instance instance = (MonitorEc2Instance) selectedObject;

		}

		private void doShowImageInfo() {
			ImageDescription imageDesc = (ImageDescription) selectedObject;
			ImageDescriptionDialog dialog = new ImageDescriptionDialog(UtilSWT
					.getShell(), SWT.NULL);

			dialog.setImageDesc(imageDesc);
			dialog.open();

		}

		public void widgetSelected(SelectionEvent e) {

			if (selectedObject instanceof GroupDescription) {
				GroupDescription ec2secGroup = (GroupDescription) selectedObject;
				log.info("Security Group Selected: " + ec2secGroup.getName());

			}

			if (selectedObject instanceof ImageDescription) {

				if (INFO.equals(action)) {
					doShowImageInfo();
					return;
				}

				ImageDescription imageDesc = (ImageDescription) selectedObject;

				List<String> groupList = Config.getInstance().getEc2Instance()
						.getSecurityGroupsInfo();
				List<String> keysList = Config.getInstance().getEc2Instance()
						.getKeyPairInfo();

				NewEc2InstanceDialog inst = new NewEc2InstanceDialog(UtilSWT
						.getShell(), SWT.NULL);

				inst.setAmi(imageDesc.getImageId());
				inst.setSecGroupList(groupList);
				inst.setKeysList(keysList);

				inst.open();

				if (inst.isAccept()) {
					boolean bStart = MessageDialog.openQuestion(UtilSWT
							.getShell(), "Start New Ec2 Instance",
							"You are about to init a new Ec2 instance:"
									+ imageDesc.getImageId());

					if (bStart) {
						log.info("Starting ec2Instace of ami: "
								+ imageDesc.getImageId());
						List<String> groupSet = inst.getSecGroupList();
						String userData = Dos2Unix.convert(inst.getUserData());
						String keyName = inst.getKeyName();

						try {
							Config.getInstance().getEc2Instance()
									.createInstance(imageDesc.getImageId(),
											groupSet, userData, keyName);
						} catch (EC2Exception e1) {
							MessageDialog.openError(UtilSWT.getShell(),
									"Error Starting Ec2 Instance", e1
											.getMessage());
							log.error(e1.getMessage());
						}
					}
				}

			}

			if (selectedObject instanceof MonitorEc2Instance) {

				if (INFO.equals(action)) {
					doShowInfo();
					return;
				}

				if (SHELL.equals(action)) {
					doShowShell();
					return;
				}

				if (MONITOR.equals(action)) {
					doShowMonitor();
					return;
				}

				MonitorEc2Instance instance = (MonitorEc2Instance) selectedObject;

				boolean bStop = MessageDialog.openQuestion(UtilSWT.getShell(),
						"Stop New Ec2 Instance",
						"You are about to Stop the Ec2 instance: "
								+ instance.getInstance().getInstanceId());

				if (bStop) {
					log.info("Starting ec2Instace of ami: "
							+ instance.getInstance().getImageId());

					try {
						List<String> instanceIds = new ArrayList<String>();
						instanceIds.add(instance.getInstance().getInstanceId());
						Config.getInstance().getEc2Instance().getEc2()
								.terminateInstances(instanceIds);
					} catch (EC2Exception e1) {
						MessageDialog.openError(UtilSWT.getShell(),
								"Error Starting Ec2 Instance", e1.getMessage());
						log.error(e1.getMessage());
					}
				}

			}

		}

	}

	/*
	 * 
	 * class UpdateEc2InstanceThread extends Thread {
	 * 
	 * MovingBoxView monitor;
	 * 
	 * int numInstances = 0;
	 * 
	 * double lastValue = 1; List<Instance> listaInstances;
	 * 
	 * UpdateEc2InstanceThread(MovingBoxView monitor ) {
	 * 
	 * this.monitor = monitor; }
	 * 
	 * public void run() {
	 * 
	 * while (true){ try { sleep(2000); } catch (InterruptedException e) {
	 *  }
	 * 
	 * listaInstances = Config.getInstance().getEc2Instance().checkInstances();
	 * if (listaInstances != null){ numInstances = listaInstances.size(); }
	 * else{ numInstances = 0; }
	 * 
	 * log.info("updating Ec2 Instances Info " + numInstances);
	 * 
	 * 
	 * Config.getInstance().getDisplay().asyncExec(new Runnable() { public void
	 * run(){
	 * 
	 * final IWorkbench workbench = PlatformUI.getWorkbench(); if (workbench ==
	 * null) return; final Display display = workbench.getDisplay();
	 * 
	 * if (!display.isDisposed()){ log.info("updating chart numInstances " +
	 * numInstances); monitor.getInstancesNode().getEc2Instances().clear();
	 * 
	 * for (Instance instance:listaInstances){
	 * monitor.getInstancesNode().getEc2Instances().add(new
	 * Ec2Instance(instance)); //TreeEc2Instance to = new
	 * TreeEc2Instance(instance); //p2.addChild(to); }
	 * 
	 * monitor.getTreeViewer().refresh(); } } });
	 * 
	 *  }
	 *  } }
	 * 
	 */

	public TreeViewer getTreeViewer() {
		return treeViewer;
	}

	public Ec2Info getRoot() {
		return root;
	}

	public Ec2Info getInstancesNode() {
		return instancesNode;
	}
}
